package com.sf.wisdomkg.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.andview.refreshview.XRefreshView;
import com.sf.wisdomkg.R;
import com.sf.wisdomkg.RecyclerView.RecycleViewDivider;
import com.sf.wisdomkg.adapter.HomeInfoListAdapter;
import com.sf.wisdomkg.utils.CommonUtils;
import com.sf.wisdomkg.utils.MyOnItemClickListener;
import com.sf.wisdomkg.xRefreshView.CustomFooterView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by ming on 2017/9/22.
 */
public class HomeInfoActivity extends AppCompatActivity implements View.OnClickListener{
    private static final String SHARE_CONTENT = "app_";
    private SharedPreferences setting;


    private String baseUrl = null;

    //UI
    private Button back_btn;
    private TextView bar_content;
    private TextView Zan_wu;

    //展示数据
    private RecyclerView recyclerView;
    private XRefreshView xRefreshView;
    private HomeInfoListAdapter adapter;
    private LinearLayoutManager layoutManager;
    private ArrayList<HashMap<String, String>> info_list;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_info);
        getSupportActionBar().hide();
        initView();
        initRefreshView();
//        requestData();
        bar_content.setText("信息公告");
        back_btn.setOnClickListener(this);
    }
    /**
     * 初始化
     */
    private void initView(){
        setting = this.getSharedPreferences(SHARE_CONTENT,0);
        if (setting.getString("roleId","").equals("2")){
            baseUrl = CommonUtils.IP_S + CommonUtils.M_T;
        }else if (setting.getString("roleId","").equals("3")){
            baseUrl = CommonUtils.IP_S + CommonUtils.M_S;
        }else if (setting.getString("roleId","").equals("1")){
            baseUrl = CommonUtils.IP_S + CommonUtils.M_T;
        }


        back_btn = (Button)findViewById(R.id.back_btn);
        bar_content = (TextView) findViewById(R.id.bar_content);
        Zan_wu = (TextView)findViewById(R.id.Zan_wu);

        info_list = new ArrayList<>();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.back_btn:
                finish();
                break;
        }
    }

    /**
     * 初始化下拉刷新部分
     */
    private void initRefreshView() {
        xRefreshView = (XRefreshView) findViewById(R.id.xrefreshview);
        xRefreshView.setPullLoadEnable(true);
        recyclerView = (RecyclerView) findViewById(R.id.recycler_view_test_rv);
        recyclerView.setHasFixedSize(true);
        recyclerView.addItemDecoration(new RecycleViewDivider(HomeInfoActivity.this, LinearLayoutManager.HORIZONTAL, R.drawable.recyclerview_divider));
        adapter = new HomeInfoListAdapter(info_list, HomeInfoActivity.this);
        // 设置静默加载模式
//        xRefreshView1.setSilenceLoadMore();
        layoutManager = new LinearLayoutManager(HomeInfoActivity.this);
        recyclerView.setLayoutManager(layoutManager);
        // 静默加载模式不能设置footerview
        recyclerView.setAdapter(adapter);
        //设置刷新完成以后，headerview固定的时间
        xRefreshView.setPinnedTime(1000);
        xRefreshView.setPullLoadEnable(false);
        xRefreshView.setMoveForHorizontal(false);
        xRefreshView.setAutoLoadMore(true);
        xRefreshView.startRefresh();
        xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {

            @Override
            public void onRefresh(boolean isPullDown) {
                getNewInfo();
                


            }

            @Override
            public void onLoadMore(boolean isSilence) {

                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        xRefreshView.stopLoadMore();
                    }
                }, 2000);
            }
        });
        adapter.setOnItemClickListener(new MyOnItemClickListener() {
            @Override
            public void OnItemClickListener(View view, int position) {

                String id = info_list.get(position).get("id");
                Intent intent = new Intent(HomeInfoActivity.this, HomeInfoDescActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("id",id);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
    }

    /**
     * 加载数据部分
     */
    public void requestData() {

        if (adapter.getCustomLoadMoreView() == null) {
            adapter.setCustomLoadMoreView(new CustomFooterView(HomeInfoActivity.this));
        }

        adapter.setData(info_list);
    }

    /**
     * 获取信息公告详情
     */
    private void getNewInfo() {

        RequestParams params = new RequestParams(baseUrl + "notice/noticeList");
        //联网设置
        params.setCacheMaxAge(1000 * 60);
        params.setConnectTimeout(9000);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                xRefreshView.stopRefresh();
                xRefreshView.stopLoadMore();
                //解析result
                if (result != null) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (jsonObject.optString("status").equals("true")) {
                            try {
                                JSONArray jsonArr = new JSONArray(jsonObject.optString("data"));

                                for (int i = 0; i < jsonArr.length(); i++) {
                                    HashMap<String, String> hashMap = new HashMap<>();
                                    JSONObject jsObj = new JSONObject();
                                    jsObj = jsonArr.getJSONObject(i);
                                    hashMap.put("id", jsObj.optString("id"));
                                    hashMap.put("name", jsObj.optString("name"));
                                    hashMap.put("content", jsObj.optString("content"));
                                    hashMap.put("user",jsObj.optString("user"));
                                    hashMap.put("createTime",jsObj.optString("createTime"));
                                    info_list.add(hashMap);
                                }
                                requestData();

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

                Toast.makeText(HomeInfoActivity.this, "连接服务器失败,请检查网络！" + ex, Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Toast.makeText(HomeInfoActivity.this, "请求超时,请检查网络！", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {
                xRefreshView.stopRefresh();
                xRefreshView.stopLoadMore();
            }
        });
    }
}
